/*
 * @Descripttion: GGB
 * @version: 1.0
 * @Author: GGB
 * @Date: 2022-01-18 06:57:22
 * @LastEditors: GGB
 * @LastEditTime: 2022-01-18 07:18:03
 */
import { useState, useEffect } from 'react'
const useKeyPress = (targetKeyCode) => { 
    const [keyPressed, setKeyPressed] = useState(false)
    const keyDownHandler = ({ keyCode }) => {
        if (keyCode === targetKeyCode) {
            setKeyPressed(true)
        } 
    }
    const keyUpHandler = ({ keyCode }) => {
        if (keyCode === targetKeyCode) {
            setKeyPressed(false)
        }
    }
    /**
     * 加载时添加移除时去掉
     */
    useEffect(() => {
        document.addEventListener('keydown', keyDownHandler)
        document.addEventListener('keyup', keyUpHandler)
        return () => {
            document.removeEventListener('keydown', keyDownHandler)
            document.removeEventListener('keyup', keyUpHandler)
        }
    },[])
    return keyPressed
}

export default useKeyPress;